# exerc3.py
import csv


def load_data(filename):
    """加载CSV数据（自动尝试常见中文编码）"""
    encodings = ['gb18030', 'utf-8', 'gbk']
    for enc in encodings:
        try:
            with open(filename, encoding=enc) as f:
                headers = next(csv.reader(f))
                return headers, [row for row in csv.reader(f)]
        except UnicodeDecodeError:
            continue
    raise ValueError("无法解码文件")


def search_data(headers, data):
    """交互式查询数据（支持多项目文字查询）"""
    provinces = [row[0] for row in data]
    items = headers[1:]

    print("可用消费项目:", ", ".join(items))

    while True:
        print("\n" + "=" * 30)
        province = input("输入查询省份（q退出）: ").strip()
        if province.lower() == 'q':
            break

        if province not in provinces:
            print("省份不存在，请重新输入！")
            continue

        input_items = input("输入要查询的项目名称（多个用逗号隔开）: ").strip()
        query_items = [item.strip() for item in input_items.split(",")]

        # 验证所有输入的项目是否有效
        invalid_items = [item for item in query_items if item not in items]
        if invalid_items:
            print(f"以下项目不存在: {', '.join(invalid_items)}")
            print("可用项目:", ", ".join(items))
            continue

        # 查找并显示结果
        result = next(row for row in data if row[0] == province)
        print(f"\n查询结果 - {province}:")
        for item in query_items:
            value = result[headers.index(item)]
            print(f"  {item}: {value}")


if __name__ == "__main__":
    try:
        headers, data = load_data("xiaofei.csv")
        search_data(headers, data)
    except FileNotFoundError:
        print("错误: 未找到xiaofei.csv文件")
    except Exception as e:
        print(f"发生错误: {e}")